<template>
  <ve-modal
    title="修改已选承租人信息"
    :okLoading="okLoading"
    v-model="visible"
    cancelText="取消"
    @close="visible = false"
    @confirm="onConfirm"
  >
    <ve-form :model="form" ref="formRef" :rules="formRules">
      <ve-form-item prop="memberName" label="承租人" required class="memberName-class">
        <!-- <ve-input v-model="form.memberName" /> -->
        <ve-input v-model="form.memberName" type="textarea" :maxlength="50" :autoHeight="true" placeholder="请输入" />
      </ve-form-item>
      <ve-form-item label="联系电话" prop="memberPhone" required>
        <ve-input v-model="form.memberPhone" @clear="isAlreadyExists = false" @input="isAlreadyExists = false" :maxlength="11" />
      </ve-form-item>
    </ve-form>
    <view style="display: flex; justify-content: flex-end">
      <ve-button
        v-if="isCommonContract && isAlreadyExists"
        :customStyle="{ margin: '10px 0' }"
        @click="changeMemberFn"
        type="plain"
        size="mini"
        >使用此手机号的承租人生成合同</ve-button
      >
    </view>
  </ve-modal>
  <ve-toast ref="toastRef" />
  <!-- 二次确认 -->
  <ve-confirm titleText="提示" asyncClose v-model="confirmVisible" @confirm="confirmSubmit">
    <view>{{ confirmMemberMsg }}</view>
  </ve-confirm>
</template>

<script setup>
  import { ref, watchEffect } from 'vue'
  import { updateMemberLOrderAPI, updateMemberSOrderAPI, checkMemberAPI } from '@/api/order/order'

  const props = defineProps({
    orderType: {
      type: String,
      default: 'sOrder',
    },
    mode: {
      type: String,
      default: 'updateMember',
    },
    isCommonContract: {
      type: Boolean,
      default: false,
    },
  })
  const emit = defineEmits(['ok', 'changeMember'])

  const fetchAPI = props.orderType == 'sOrder' ? updateMemberSOrderAPI : updateMemberLOrderAPI

  const visible = ref(false)
  const form = ref({})
  let formRules = {
    memberName: { required: true, message: '请输入' },
    memberPhone: [
      { required: true, message: '请输入联系电话' },
      { len: 11, match: /^[0-9]+$/, message: '仅支持数字，长度11位' },
    ],
  }

  const orderInfo = ref({})
  const open = (record) => {
    orderInfo.value = record
    visible.value = true
    // 初始化
    form.value = {
      id: record.memberId,
      memberName: record.memberName,
      memberPhone: record.memberPhone,
    }
  }
  // 点击确认
  const formRef = ref()
  const toastRef = ref()
  const onConfirm = () => {
    formRef.value.validate((valid) => {
      if (valid) {
        preCheck()
      }
    })
  }

  // 预先校验 是否修改会员
  const okLoading = ref(false)
  const confirmMemberMsg = ref('')
  const confirmVisible = ref(false)
  const isAlreadyExists = ref(false)
  const preCheck = () => {
    okLoading.value = true
    // 监听 customer 组件 memberPhoneFetching 完成
    toastRef.value.showLoading()
    // 合同记录中，不请求checkmember接口
    if (props.mode == 'notFetch') {
      okLoading.value = false
      confirmMemberMsg.value = '确认修改承租人信息吗？'
      toastRef.value.hideLoading()
      confirmVisible.value = true
      return
    }
    checkMemberAPI({
      id: form.value.id,
      phone: form.value.memberPhone,
      name: form.value.memberName,
      type: 2,
    })
      .then((res) => {
        okLoading.value = false
        const msg = res.result.msg || '确认修改承租人信息吗？'
        confirmMemberMsg.value = msg
        // 二次确认
        toastRef.value.hideLoading()
        confirmVisible.value = true
      })
      .catch(({ data }) => {
        isAlreadyExists.value = data.message && data.message.indexOf('联系电话已存在') > -1
        toastRef.value.hideLoading()
      })
      .finally(() => {
        okLoading.value = false
      })
  }

  // 确认
  const confirmSubmit = () => {
    confirmVisible.value = false
    visible.value = false
    if (props.mode == 'edit') {
      emit('ok', { ...form.value })
    } else {
      fetchSubmit()
    }
  }
  // 访问api
  const fetchSubmit = () => {
    const orderInfoVal = orderInfo.value
    const param = {
      id: orderInfoVal.id,
      clientId: orderInfoVal.clientId,
      memberId: orderInfoVal.memberId,
      memberPhone: form.value.memberPhone,
      memberName: form.value.memberName,
    }
    fetchAPI(param)
      .then(() => {
        visible.value = false
        toastRef.value.show({
          title: '操作成功',
          type: 'success',
        })
        emit('ok')
      })
      .catch(() => {
        toastRef.value.hideLoading()
      })
  }
  const changeMemberFn = () => {
    emit('changeMember', {
      memberPhone: form.value.memberPhone,
      memberName: form.value.memberName,
    })
  }
  const close = () => {
    confirmVisible.value = false
    visible.value = false
  }

  watchEffect(() => {
    visible.value && (isAlreadyExists.value = false)
  })

  defineExpose({
    open,
    close,
  })
</script>
<style lang="less" scoped>
  .memberName-class {
    /deep/ .ve-form-item__body {
      align-items: center;
    }
  }
</style>
